package com.YCH.behavior.service.impl;

import com.YCH.behavior.service.AppReadBehaviorService;
import com.YCH.model.behavior.dtos.ReadBehaviorDto;
import com.YCH.model.behavior.pojos.TbReadBehavior;
import com.YCH.model.common.dtos.ResponseResult;
import com.YCH.model.common.enums.AppHttpCodeEnum;
import com.YCH.model.mappers.app.TbReadBehaviorMapper;
import com.YCH.model.user.pojos.TbUser;
import com.YCH.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@SuppressWarnings("all")
public class AppReadBehaviorServiceImpl implements AppReadBehaviorService {

    @Autowired
    private TbReadBehaviorMapper apReadBehaviorMapper;

    @Override
    public ResponseResult saveReadBehavior(ReadBehaviorDto dto) {

        //获取用户信息，获取设备id
        // 1.校验参数
        TbUser user = AppThreadLocalUtils.getUser();
        // 用户和用户id不能同时为空
        if (user == null && dto.getUserId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        Long userId = null;
        if (user != null) {
            userId = user.getId();
        }
        if(dto.getUserId()!=null){
            userId = dto.getUserId();
        }
        //查询
        TbReadBehavior apReadBehavior = apReadBehaviorMapper.selectByUserId(userId, dto.getArticleId());
        boolean isInsert = false;
        if(apReadBehavior==null){
            isInsert = true;
            apReadBehavior= new TbReadBehavior();
        }
        apReadBehavior.setUserId(userId);
        apReadBehavior.setCount(dto.getCount());
        apReadBehavior.setPercentage(dto.getPercentage());
        apReadBehavior.setLoadDuration(dto.getLoadDuration());
        apReadBehavior.setArticleId(dto.getArticleId());
        apReadBehavior.setModifyTime(new Date());
        apReadBehavior.setCreatTime(new Date());
        apReadBehavior.setReadDuration(dto.getReadDuration());
        int count = 0;
        if(isInsert){
            count= apReadBehaviorMapper.insert(apReadBehavior);
        }else{
            count =apReadBehaviorMapper.update(apReadBehavior);
        }

        return ResponseResult.okResult(count);
    }
}
